<template>
  <div class="article-list">
    <div v-for="article in articles" :key="article.id" class="article-item"  @click="viewArticle(article.id)">
      <h2 class="article-title">
        {{ article.title }}
      </h2>
      <p class="article-summary">{{ article.summary }}</p>
      <div class="article-meta">
        <span class="article-type">{{ article.type }}</span>
        <span class="article-date">{{ formatDate(article.createTime) }}</span>
      </div>
    </div>
  </div>
</template>
<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getArticleList } from '@/api/articles'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

export default {
  name: 'ArticleList',
  setup() {
    const articles = ref([])
    const router = useRouter()

    const fetchArticles = async () => {
      try {
        const res = await getArticleList()
        articles.value = res.data
      } catch (error) {
        ElMessage.error('获取文章列表失败')
      }
    }

    const viewArticle = (id) => {
      router.push({ name: 'ArticleDetail', params: { id } }) // 将 'Article' 改为 'ArticleDetail'
    }

    const formatDate = (date) => {
      return dayjs(date).format('YYYY-MM-DD')
    }

    onMounted(fetchArticles)

    return {
      articles,
      viewArticle,
      formatDate,
    }
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/styles/variables.scss';

.article-list {
  max-width: 700px;
  margin: 0 auto;
  padding: $spacing-large 0;
}

.article-item {
  background-color: white;
  padding: $spacing-large;
  border-bottom: 1px solid $border-color;
  border-radius: 10px;
  &:last-child {
    border-bottom: none;
  }
}

.article-title {
  font-size: $font-size-large;
  color: $text-color;
  margin: 0 0 $spacing-small;
  cursor: pointer;

  &:hover {
    color: $primary-color;
  }
}

.article-summary {
  font-size: $font-size-medium;
  color: $text-color;
  margin-bottom: $spacing-medium;
  line-height: 1.5;
}

.article-meta {
  font-size: $font-size-small;
  color: $text-color-secondary;
}

.article-type {
  margin-right: $spacing-medium;
}
</style>
